package cn.picclife.mwx.common.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 支持跨域请求的过滤器
 * 
 * @ClassName: CorsFilter
 * @Description: TODO
 * @author Mengmeng.Kang
 * @date 2016年7月15日 下午4:01:02
 *
 */
public class CorsFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		CorsUtil corsUtil = new CorsUtil();
		if (corsUtil.isPreflight(request)) {
			// 如果是cors preflight request则设置cors预检权限
			corsUtil.allowPreflightPermit(request, response);
			// 返回204状态
			((HttpServletResponse) response).setStatus(204);
			// 直接返回不做后续处理
			return;
		} else {
			// 如果是cors actual request则设置相关cors权限
			corsUtil.allowActualPermit(request, response);
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

}
